package com.corgi.multi.anno.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @类名：         <p>SpringContextHolder</p>
 * @功能描述： <p>TODO<p>
 * @作者信息： <p>dengmiao<p>
 * @创建时间： <p>2018年5月12日下午5:57:16<p>
 * @修改备注：
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {

	/**  
	 * 上下文对象实例,可在任意代码中取出ApplicaitonContext.  
	 */
	private static ApplicationContext applicationContext = null;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		if(SpringContextHolder.applicationContext == null)
			SpringContextHolder.applicationContext = applicationContext;
		
		System.out.println("---------------------------------------------------------------------");
		System.out.println("---------------------------------------------------------------------");
		System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取 applicationContext对象,applicationContext="+SpringContextHolder.applicationContext+"========");
		System.out.println("---------------------------------------------------------------------"); 
	}

	public static ApplicationContext getApplicationContext() {    
		return applicationContext;    
	}    
	/**  
	 * 通过name获取 Bean.
	 */    
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		return (T) getApplicationContext().getBean(name);    
	}

	/**
	 * 通过class获取Bean.
	 */
	public static <T> T getBean(Class<T> clazz){  
		return getApplicationContext().getBean(clazz);  
	}

	/**
	 * 通过name,以及Clazz返回指定的Bean 
	 * @return
	 */
	public static <T> T getBean(String name,Class<T> clazz){  
		return getApplicationContext().getBean(name, clazz);  
	}

}
